package vip.xls8z.thread.pool.learning;

import java.time.LocalDateTime;
import java.util.concurrent.*;

public class TheadPoolExecutorTest {
    public static void main(String[] args) throws InterruptedException {
        // 核心线程数
        int corePoolSize = 1;
        // 最大线程数
        int maximumPoolSize = 5;
        // 非核心线程的存活时间
        long keepAliveTime = 60;
        // 存活时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        // 阻塞队列
        BlockingQueue<Runnable> workQueue = new SynchronousQueue<>();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue);

        // 拒绝策略
        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        try {
            for (int i = 0; i < 10; i++) {
                final int idx = (i + 1);
                threadPoolExecutor.execute(() -> {
                    try {
                        Thread.sleep(1000);
                        System.out.println(LocalDateTime.now() + ", 这是第 [ " + idx + " ] 个任务, 当前执行线程为: [ " + Thread.currentThread().getName() + " ].");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }






    }
}
